package com.ferryc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ferryc.entity.Stroage;
import com.ferryc.entity.StroageDetail;
import com.ferryc.exception.UnderstockException;
import com.ferryc.mapper.StroageDetailMapper;
import com.ferryc.service.IStroageService;
import com.ferryc.mapper.StroageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Ferry Chen on 2019-11-06.
 */
@Service
@Slf4j
public class StroageServiceImpl extends ServiceImpl<StroageMapper, Stroage> implements IStroageService {

    @Autowired
    private StroageMapper stroageMapper;

    @Autowired
    private StroageDetailMapper stroageDetailMapper;

    @Override
    @Transactional
    public boolean save(Stroage entity) {
        Stroage qs = new Stroage();
        qs.setProductId(entity.getProductId());
        List<Stroage> list = stroageMapper.queryList(qs);
        String id = UUID.randomUUID().toString();
        if (!CollectionUtils.isEmpty(list)) {
            id = list.get(0).getId();
            entity.setId(id);
            entity.setCount(entity.getCount() + list.get(0).getCount());
            entity.setUpdateTime(new Date());
            saveDetail("1", id, entity.getCount());
            return super.saveOrUpdate(entity);
        } else {
            entity.setId(id);
            saveDetail("1", id, entity.getCount());
            return super.save(entity);
        }
    }

    @Override
    @Transactional
    public void consume(Stroage stroage) {
        Stroage qs = new Stroage();
        qs.setProductId(stroage.getProductId());
        List<Stroage> list = stroageMapper.queryList(qs);
        if (!CollectionUtils.isEmpty(list)) {
            if (list.get(0).getCount() < stroage.getCount()) {
               throw   new UnderstockException();
            }
            saveDetail("2", list.get(0).getId(), stroage.getCount());
            stroage.setId(list.get(0).getId());
            stroage.setCount(list.get(0).getCount() - stroage.getCount());
            stroage.setUpdateTime(new Date());

            super.saveOrUpdate(stroage);
        }
    }

    @Override
    public List<Stroage> queryList(Stroage stroage) {
        return stroageMapper.queryList(stroage);
    }

    private void saveDetail(String type, String id, int count) {
        StroageDetail sd = new StroageDetail();
        sd.setStroageId(id);
        sd.setType(type);
        sd.setCount(count);
        sd.setInsertTime(new Date());
        stroageDetailMapper.insert(sd);
    }
}
